package com.project.web.util.handler;

import com.google.gson.Gson;
import com.project.common.core.utils.SpringUtils;
import com.project.common.core.utils.exception.CustomException;
import com.project.web.util.builder.TextBuilder;
import com.project.web.wechat.model.app.WxBizCropTag;
import com.project.web.wechat.service.app.WxBizCropTagService;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.cp.api.WxCpExternalContactService;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.external.WxCpUpdateRemarkRequest;
import me.chanjar.weixin.cp.bean.external.contact.WxCpExternalContactInfo;
import me.chanjar.weixin.cp.bean.message.WxCpXmlMessage;
import me.chanjar.weixin.cp.bean.message.WxCpXmlOutMessage;
import me.chanjar.weixin.cp.constant.WxCpConsts;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 通讯录变更事件处理器.
 *
 * @author wyy
 */
@Component
public class ExternalContactChangeHandler extends AbstractHandler {

    public static final Logger log = LoggerFactory.getLogger(ExternalContactChangeHandler.class);

    @Override
    public WxCpXmlOutMessage handle(WxCpXmlMessage wxMessage, Map<String, Object> context, WxCpService cpService, WxSessionManager sessionManager) {
        String content = new Gson().toJson(wxMessage);
        log.info("\r\n *********添加企业客户事件内容：{}", content);
        // 获取state自定义参数【渠道码】、事件类型、
        String changeType = wxMessage.getChangeType();
        if (WxCpConsts.ExternalContactChangeType.ADD_EXTERNAL_CONTACT.equalsIgnoreCase(changeType)) {
            log.info("\r\n *********进入客户标签修改************");
            addExternalContact(wxMessage, cpService);

        }

        return new TextBuilder().build(content, wxMessage, cpService);
    }

    /**
     * 客户新增事件处理
     *
     * @param wxMessage
     */
    void addExternalContact(WxCpXmlMessage wxMessage, WxCpService cpService) {
        // 获取参数
        String userId = wxMessage.getUserId();
        String externalUserId = wxMessage.getExternalUserId();
        String wxBizCropTagId = wxMessage.getState();

        // 根据企业标签ID查询标签
        Object wxBizCropTagServiceImpl = SpringUtils.getBean("wxBizCropTagServiceImpl");
        WxBizCropTagService wxBizCropTagService = (WxBizCropTagService) wxBizCropTagServiceImpl;
        WxBizCropTag cropTag = wxBizCropTagService.getById(Long.valueOf(wxBizCropTagId));
        String tagId = cropTag.getTagId();

        // 设置标签
        WxCpExternalContactService contactService = cpService.getExternalContactService();

        try {
            // 修改客户标签
            contactService.markTag(userId, externalUserId, new String[]{tagId}, null);
            log.info("\r\n *********客户标签修改成功************");

            // 修改客户备注
            String remarkPrefix = cropTag.getRemarkPrefix();
            if (StringUtils.isNotBlank(remarkPrefix)) {
                // 获取客户详情
                WxCpExternalContactInfo externalContact = contactService.getContactDetail(externalUserId);
                WxCpUpdateRemarkRequest wxCpExternalContactRemark = new WxCpUpdateRemarkRequest();
                wxCpExternalContactRemark.setUserId(userId);
                wxCpExternalContactRemark.setExternalUserId(externalUserId);
                wxCpExternalContactRemark.setRemark(remarkPrefix + "-" + externalContact.getExternalContact().getName());
                wxCpExternalContactRemark.setDescription(cropTag.getTagName());
                contactService.updateRemark(wxCpExternalContactRemark);
                log.info("\r\n *********客户备注修改成功************");
            }

            // 查询欢迎语
//            Object wxBizWelcomeMsgServiceImpl = SpringUtils.getBean("wxBizWelcomeMsgServiceImpl");
//            WxBizWelcomeMsgService wxBizWelcomeMsgService = (WxBizWelcomeMsgService) wxBizWelcomeMsgServiceImpl;
//            WxBizWelcomeMsg welcomeMsg = wxBizWelcomeMsgService.getByChannelAndUserId(userId, channelCode);
//            if (null != welcomeMsg) {
//                log.info("\r\n *********尖刀特训欢迎语************");
//                Map<String, Object> welMap = new HashMap<>();
//                welMap.put("welcome_code", wxMessage.getWelcomeCode());
//                Map<String, Object> contentMap = new HashMap<>();
//                contentMap.put("content", welcomeMsg.getTextContent());
//                welMap.put("text", contentMap);
//                String msgJson = new Gson().toJson(welMap);
//                contactService.sendWelcomeMsg(msgJson);
//            }

        } catch (WxErrorException e) {
            log.error("客户新增事件处理出错：{}", ExceptionUtils.getStackTrace(e));
            throw new CustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
        }
    }

}
